from django import template
from django.core.urlresolvers import reverse
from urllib import quote
import random

register = template.Library()

CLOUD_SIZE = 40

def make_tags(rows):
    for name, in rows:
        si = random.random() #si = size indicator
        yield u'<div class="%(size)s"><a href="%(url)s">%(name)s</a></div>' % {
            'size': (u' small' if si < .1 else
                     u'' if si < .5 else
                     u' big' if si < .85 else
                     u' verybig'),
            'url': reverse('ims.sti.views.topic', args=(quote(name.encode('utf-8')),)),
            'name': name}


@register.simple_tag
def topics_cloud():
    sql = """
    select sti_topic.name 
    from sti_topic_aux, sti_topic 
    where topic_id = sti_topic.id 
    group by topic_id
    having count(*) > 2
    order by rand()
    limit %i
    """ % CLOUD_SIZE

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()

    return u'\n'.join(make_tags(rows))

